<?php

class ProfilesController extends Controller
{
	public $layout = '//layouts/usersMembersProfile';
	public function filters()
	{
		return array(
			'accessControl',
		);
	}
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',
				'actions'=>array('index'),
				'users'=>array('*'),
			),
			array('allow',
				'actions'=>array(''),
				'users'=>array('?'),
			),
			array('allow',
				'actions'=>array('eventMe','eventOrder', 'deleteWork','addStudy','addWork',
					'updateWork','changeAccount','work', 'changeEmail','info', 
					'changePassword','study','deleteStudy','updateStudy','updateInfo'),
				'users'=>array('@'),
			),
			array('deny',
				'users'=>array('*'),
			),
		);
	}
    
    public function actionEventOrder($id){
        if ($id !== Yii::app()->user->id) {
            $this->redirect(array('/Users/profiles/eventOrder', 'id'=>Yii::app()->user->id));
        }
		$criteria = new CDbCriteria;
        $criteria->condition = 't.status="A"';
		$criteria->with = array('orders'=>array(
			'joinType'=>'INNER JOIN',
			'condition'=>'orders.member_id='.$id,
            'together'=>true
		));
		$dataProvider=new CActiveDataProvider('Events',
			array(
				'criteria'=>$criteria,
				'sort'=>array(
					'defaultOrder'=>'updatedate DESC, posteddate DESC, startdate ASC, enddate DESC',
				),
				'pagination'=>array(
					'pageSize'=>10,
					'pageVar'=>'page',
				),
			)
		);
		
		$this->render('eventOrder', array(
			'dataProvider'=>$dataProvider,
		));
	}

	public function actionEventMe($id){
        if ($id !== Yii::app()->user->id) {
            $this->redirect(array('/Users/profiles/eventOrder', 'id'=>Yii::app()->user->id));
        }
        
		$criteria = new CDbCriteria;
		$criteria->condition = 'member_id=' . $id;
		$dataProvider=new CActiveDataProvider('Events',
			array(
				'criteria'=>$criteria,
				'sort'=>array(
					'defaultOrder'=>'updatedate DESC, posteddate DESC, startdate ASC, enddate DESC',
				),
				'pagination'=>array(
					'pageSize'=>10,
					'pageVar'=>'page',
				),
			)
		);
		
		$this->render('eventMe', array(
			'dataProvider'=>$dataProvider,
		));
	}

	public function actionDeleteWork()
	{
		$model=MemberWorks::model()->findByPk($_POST['id']);
		if (count($model) != 0) {
			$model->delete();	
		}
	}
	public function actionDeleteStudy()
	{
		$model=MemberStudies::model()->findByPk($_POST['id']);
		if (count($model) != 0) {
			$model->delete();	
		}
	}
	public function actionUpdateInfo()
	{
		$model=Members::model()->findByPk(Yii::app()->user->id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Members']))
        {
        	// $model->member_id = Yii::app()->user->id;
         //    $model->attributes=$_POST['MemberStudies'];
         //    if($model->save()){

         //    	echo CJSON::encode(array(
         //    			'view'=>$this->renderPartial('_viewonestudy',array('study'=>$model),true),
         //    		));
         //    }
        }else{
        	$this->renderPartial('_forminfo',array(
	            'model'=>$model,
	        ),false,true);
        }	
	}
	public function actionUpdateStudy()
	{
		$model=MemberStudies::model()->findByPk($_GET['id']);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['MemberStudies']))
        {
        	$model->member_id = Yii::app()->user->id;
            $model->attributes=$_POST['MemberStudies'];
            if($model->save()){
            	$this->redirect(array('study','id'=>$model->member_id));
            }
        }else{
	        echo CJSON::encode(array(
            			'view'=>$this->renderPartial('_updatestudy',array('model'=>$model),true),
            		));
        }	
	}
	public function actionUpdateWork()
	{
		$model=MemberWorks::model()->findByPk($_REQUEST['id']);
        if(isset($_POST['MemberWorks']))
        {
        	$model->member_id = Yii::app()->user->id;
            $model->attributes=$_POST['MemberWorks'];
            if($model->save()){
            	$this->redirect(array('work','id'=>$model->member_id));
            }
        }else{
        	echo CJSON::encode(array(
	        	'view'=>$this->renderPartial('_updatework',array('model'=>$model),true),
	        	));
        }	
	}

	public function actionAddstudy()
	{
		$model=new MemberStudies;

        if(isset($_POST['ajax']) && $_POST['ajax']==='member-study-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

        if(isset($_POST['MemberStudies']))
        {
        	$model->member_id = Yii::app()->user->id;
            $model->attributes=$_POST['MemberStudies'];
            if($model->save()){
            	$this->redirect(array('study','id'=>$model->member_id));
            }
        }else{
	        echo CJSON::encode(array(
					'views'=>$this->renderPartial('_formstudy',array('model'=>$model),true),
				));
        }
	}

	public function actionAddwork()
	{
			$model = new MemberWorks;
	        if(isset($_POST['ajax']) && $_POST['ajax']==='member-works-form')
			{
				echo CActiveForm::validate($model);
				Yii::app()->end();
			}
	        if(isset($_POST['MemberWorks']))
	        {
	        	$model->member_id = Yii::app()->user->id;
	            $model->attributes=$_POST['MemberWorks'];
	            if($model->save()){
	            	$this->redirect(array('work','id'=>$model->member_id));
	            }
	        }else{
	        	echo CJSON::encode(array(
					'views'=>$this->renderPartial('_formwork',array('model'=>$model),true),
				));
	        	
	        }
		 

	}
	public function actionStudy()
	{
		$works = MemberStudies::model()->findAll("member_id=".Yii::app()->user->id);
		$this->render('study',array('studys'=>$works));
	}
	public function actionWork()
	{
		$works = MemberWorks::model()->findAll("member_id=".Yii::app()->user->id);
		$this->render('work',array('works'=>$works));
	}
	public function actionChangeEmail()
	{
		$model = Members::model()->findByPk(Yii::app()->user->id);
		$model->scenario = 'changeEmail';
		
		if (isset($_POST['Members'])) {
			$model->attributes = $_POST['Members'];
			$pass = $_POST['Members']['currentPassword'];
			$status = 0;
			$json = array();
			$json['mail'] = "mail";
			$json['checkemail'] = "checkemail"; 
			$json['status'] ="rror"; 
			$json['checkuser'] = 'checkuser' ;
			$check_email_success = 0 ;
			$check_user_success = 0 ;
			if (CPasswordHelper::verifyPassword($pass,$model->password))
			{
				$mail = Members::model()->findAllByAttributes(array('email'=>$_POST['Members']['newEmail']));
				$username = Members::model()->findAllByAttributes(array('username'=>$_POST['Members']['username']));
				// check email
				if (count($mail) > 0 ) {
					$status = 1;
					$json['mail'] = "mailerror";
					$check_email_success = 1;
				}else if($_POST['Members']['newEmail'] != $_POST['Members']['confirmNewEmail'] ){
					$status = 1;
					$check_email_success = 1;
					$json['checkemail'] = "checkerror";
				}else if($_POST['Members']['newEmail'] == '' ){
					$status == 0 ;
					$json['mail'] = "cmail";
					$check_email_success = 1;
				}
				// check user
				if($_POST['Members']['username'] != $model->username && count($username) > 0 ){
					$status = 1;
					$json['checkuser'] = "checkusererror";
					$check_user_success = 1;
				}else if($_POST['Members']['username'] == '' ){
					$status == 0 ;
					$json['checkuser'] = "cuser";
					$check_user_success = 1;
				}

				// success
				if ($status == 0 ){
					if($_POST['Members']['newEmail'] != '' && $check_email_success == 0 ){
						$saveEmail = Members::model()->updateByPk(Yii::app()->user->id,array('email'=>$_POST['Members']['newEmail']));
					}
					if($_POST['Members']['username'] != '' && $check_user_success == 0 && $_POST['Members']['username'] != $model->username){
						$saveUser = Members::model()->updateByPk(Yii::app()->user->id,array('email'=>$_POST['Members']['username']));
					}
					if(isset($saveEmail) || isset($saveUser) ){
						$json['status'] ="ok";
						Yii::app()->user->logout();
					}else{
						if($json['mail'] == "cmail" || $json['checkuser'] == "cuser"){
							$json['status'] ="notchange";
						}
					}	
				}
				$status = 2;
				echo json_encode($json);
			}
			if ($status == 0) {
				echo json_encode($json);
			}
		}else{
			echo CJSON::encode(array(
					'views'=>$this->renderPartial('changeEmail',array('model'=>$model),true),
				));
		}
	}
	public function actionChangePassword()
	{
		$model = Members::model()->findByPk(Yii::app()->user->id);
		$model->scenario = 'changePassword';

		if(isset($_POST['ajax']) && $_POST['ajax']==='password-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		$status = 0;
		$json = array();
		$json['status'] ="no";
		if (isset($_POST['Members'])) {
			$model->attributes = $_POST['Members'];
			// echo "string";
			if ($model->validate())
			{
				// echo "string";
				$pass = $_POST['Members']['currentPassword'];
				if (CPasswordHelper::verifyPassword($pass, $model->password)) {
					// echo "string";
					$model->password = CPasswordHelper::hashPassword($model->newPassword);
					if ($model->save()) {
						$json['status'] ="ok";
						Yii::app()->user->logout();		
					}
				}
			}
			echo json_encode($json);
		}else{ 
			echo CJSON::encode(array(
					'views'=>$this->renderPartial('changePassword',array('model'=>$model),true),
				));
		}
	}
	public function actionIndex()
	{
		$this->render('index');
	}
	public function actionChangeAccount()
	{
		$model = Members::model()->findByPk(Yii::app()->user->id);
		$this->render('changeaccount',array('model'=>$model));
	}
	public function actionInfo()
	{
		$model = Members::model()->findByPk(Yii::app()->user->id);
		if (isset($_POST['Members'])) {
			$model->attributes = $_POST['Members'];
			$model->dateofbirth = date('Y-m-d', strtotime($_POST['Members']['dateofbirth']));
			if ($model->lname === "" || $model->fname === "" || $model->dateofbirth =="") {
				echo json_encode(array('error'=>"Không được để trống",'status'=>"empty"));
			}elseif ($model->validate())
			{
				if ($model->save()) {
					$name = $model->lname.' '.$model->fname;
					if ($model->gender == 1) {
						$gender = "Nam";
					}else{
						$gender  = "Nữ";
					}
					echo json_encode(array('name'=>$name,'gender'=>$gender,'date'=>$model->dateofbirth,'status'=>'success'));
				}else{
					echo json_encode(array('status'=>'error'));
				}
			}
		}
	}
}